package com.example.webcomen.Controller;

import com.example.webcomen.Common.AjaxResult;
import com.example.webcomen.Model.NewUser;
import com.example.webcomen.Model.User;
import com.example.webcomen.Service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class MainController {
    @Autowired
    LoginService loginService;
    @GetMapping("/")
    public String init(HttpSession session){

        return "index";
//        return "mobile";
    }
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @GetMapping("/reg")
    public String test1() {
        return "reg";
    }
    @GetMapping("/find")
    public String find(){return "find";}

    @ResponseBody
    @PostMapping("/{email}")
    public AjaxResult sendEmailCode(@PathVariable String email) {
        try {
            loginService.sendEmailCode(email);
        } catch (Exception e) {
            return AjaxResult.error("发送失败");
        }
        return AjaxResult.success("发送成功");
    }

    @ResponseBody
    @PostMapping("/new")
    public AjaxResult newUser(NewUser newUser) {
        System.out.println(newUser);
        String email = newUser.getEmail();
        String password = newUser.getPassword();
        String nickname = newUser.getNickname();
        String vercode = newUser.getVercode();
        boolean fla;
        if(loginService.validateEmailCode(vercode,email)){
            try {
                fla=loginService.registerNewUser(email,password,nickname);
                if (!fla)
                    return AjaxResult.error("ww");
            } catch (Exception e) {
                return AjaxResult.error("邮箱已存在");
            }
            return AjaxResult.success("注册成功");
        }
        return AjaxResult.error("验证码错误或已过期");
    }

}
